package com.flying.scorer;

import com.flying.common.CommonApplication;
import com.flying.refdata.DataImporter;
import com.flying.refdata.model.equity.EquityInfo;
import com.flying.refdata.service.EquityService;
import com.flying.scorer.score.ScorerWorker;
import com.flying.scorer.service.ScoreService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@SpringBootApplication
@ComponentScan(
        basePackageClasses = {
                CommonApplication.class,
                DataImporter.class,
                ScoreExporter.class},
        excludeFilters = {
                @ComponentScan.Filter(type = FilterType.REGEX, pattern = "com.flying.scorer.ScoreExporter")})

public class ScoreRunner implements CommandLineRunner {
    private static Logger logger = LoggerFactory.getLogger(ScoreRunner.class);
    @Autowired
    private ThreadPoolTaskExecutor executor;

    @Autowired
    private EquityService equityService;

    @Autowired
    private ScoreService scoreService;

    @Override
    public void run(String... args) throws Exception {
        int beginDate = 20180101;
        int endDate = 20180301;
        int units = 10;

        Collection<EquityInfo> infos = equityService.getAll();
        int i = 0;
        List<EquityInfo> splits = null;
        for (EquityInfo info : infos) {
            if (i % units == 0) {
                if (!CollectionUtils.isEmpty(splits)) dispatchToWorker(splits, beginDate, endDate);
                splits = new ArrayList<>(units);
            }
            splits.add(info);
            i++;
        }

        executor.shutdown();
    }

    private void dispatchToWorker(Iterable<EquityInfo> infos, int beginDate, int endDate) {
        ScorerWorker worker = new ScorerWorker(scoreService, infos, beginDate, endDate);
        executor.execute(worker);
    }

    public static void main(String[] args) {
        SpringApplication.run(ScoreRunner.class, args);
    }
}